<template>
    <!-- 授权用户 -->
    <el-dialog title="选择用户" v-model="visible" width="800px" top="5vh" append-to-body destroyOnClose>
        <vxe-grid ref="xGrid" v-bind="gridOptions" @checkbox-change="handleSelectionChange">
            <template #slotStatus="{ row }">
                <dict-tag :options="sys_normal_disable" :value="row.status" />
            </template>
        </vxe-grid>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="handleSelectUser">确 定</el-button>
                <el-button @click="visible = false">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts" name="SelectUser">
    import { getCurrentInstance, ref, reactive, unref } from "vue";
    import { authUserSelectAll, unallocatedUserList } from "@/api/system/role";
    import XEUtils from "xe-utils";
    import { VxeGridInstance, VxeGridProps, VxeGridListeners } from "../../../../types/index";
    const props = defineProps({
        roleId: {
            type: [Number, String],
        },
    });
    const { proxy } = getCurrentInstance() as any;
    const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
    const visible = ref(false);
    const userIds = ref([]);
    const xGrid = ref({} as VxeGridInstance);
    const queryParams: any = reactive({
        roleId: undefined,
    });

    // 显示弹框
    function show() {
        queryParams.roleId = props.roleId;
        visible.value = true;
    }

    const gridOptions = reactive<VxeGridProps>({
        border: true,
        resizable: true,
        showHeaderOverflow: true,
        showOverflow: true,
        highlightHoverRow: true,
        keepSource: true,
        id: "5",
        height: "400",
        rowId: "userId",
        autoResize: true,
        sortConfig: {
            trigger: "cell",
            remote: true,
        },
        filterConfig: {
            remote: true,
        },
        pagerConfig: {
            pageSize: 10,
            pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000],
            perfect: true,
        },
        formConfig: {
            titleWidth: 80,
            titleAlign: "right",
            items: [
                {
                    field: "userName",
                    title: "用户名称",
                    span: 9,
                    itemRender: { name: "$input", props: { placeholder: "请输入用户名称" } },
                },
                {
                    field: "phonenumber",
                    title: "手机号码",
                    span: 9,
                    itemRender: { name: "$input", props: { placeholder: "请输入手机号码" } },
                },
                {
                    itemRender: {
                        name: "$buttons",
                        children: [
                            {
                                props: {
                                    type: "submit",
                                    content: "查询",
                                    status: "primary",
                                },
                            },
                            {
                                props: {
                                    type: "reset",
                                    content: "重置",
                                },
                            },
                        ],
                    },
                },
            ],
        },
        toolbarConfig: {
            refresh: true,
            zoom: true,
            custom: true,
        },
        proxyConfig: {
            paramsChangeLoad: false, //额外的请求参数改变时是否重新请求数据
            seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
            sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
            filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
            form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
            // 对应响应结果 { result: [], page: { total: 100 } }
            props: {
                result: "rows", // 配置响应结果列表字段
                total: "total", // 配置响应结果总页数字段
            },
            ajax: {
                // 接收 Promise
                query: ({ page, sorts, filters, form, params }: any) => {
                    const queryParams: any = Object.assign({}, form);
                    // 处理排序条件
                    const orderByColumn = <Array<String>>[];
                    const isAsc = <Array<Boolean>>[];
                    sorts.forEach((m: any) => {
                        orderByColumn.push(m.field);
                        isAsc.push(m.order);
                    });
                    queryParams.orderByColumn = orderByColumn.join(",");
                    queryParams.isAsc = isAsc.join(",");
                    // 处理筛选条件
                    filters.forEach(({ property, values }: any) => {
                        queryParams[property] = values.join(",");
                    });
                    return unallocatedUserList({
                        page: {
                            current: page.currentPage,
                            size: page.pageSize,
                        },
                        roleId: props.roleId,
                        ...queryParams,
                        ...params,
                    }).then((response) => {
                        return response;
                    });
                },
            },
        },
        columns: [
            { type: "checkbox", width: 60 },
            {
                field: "userName",
                title: "用户名称",
                sortable: true,
            },
            {
                field: "nickName",
                title: "用户昵称",
                sortable: true,
            },
            {
                field: "email",
                title: "邮箱",
                sortable: true,
            },
            {
                field: "phonenumber",
                title: "手机",
                sortable: true,
            },
            {
                field: "status",
                title: "状态",
                filters: sys_normal_disable,
                slots: {
                    default: "slotStatus",
                },
            },
            {
                field: "createTime",
                title: "创建时间",
                visible: false,
                sortable: true,
                formatter({ cellValue }: any) {
                    return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
                },
            },
        ],
        checkboxConfig: {
            labelField: "userId",
            reserve: true,
            highlight: true,
            range: true,
        },
    });

    /**选择行 */
    function clickRow(row: any) {
        proxy.$refs["refTable"].toggleRowSelection(row);
    }
    // 多选框选中数据
    function handleSelectionChange(selection: any) {
        userIds.value = selection.records.map((item: any) => item.userId);
    }

    const emit = defineEmits(["ok"]);
    /** 选择授权用户操作 */
    function handleSelectUser() {
        const roleId = queryParams.roleId;
        const uIds = userIds.value.join(",");
        if (uIds == "") {
            proxy.$modal.msgError("请选择要分配的用户");
            return;
        }
        authUserSelectAll({ roleId: roleId, userIds: uIds }).then((res: any) => {
            proxy.$modal.msgSuccess(res.msg);
            if (res.code === 200) {
                visible.value = false;
                emit("ok");
            }
        });
    }

    defineExpose({
        show,
    });
</script>
